//
//  PhotoBrowserAnimator.swift
//  weibo
//
//  Created by 张宏芝 on 15/9/14.
//  Copyright © 2015年 kama. All rights reserved.
//

import UIKit
import SDWebImage

// 专门提供从控制器到照片浏览器modal'转场'动画的对象
class PhotoBrowserAnimator: NSObject,UIViewControllerTransitioningDelegate {
//    是否展现的标记
    var isPresented = false
//    其实的位置
    var fromRect = CGRectZero
//    目标的位置
    var toRect = CGRectZero
//    图像视图的URL
    var url:NSURL?
//    动画播放的图像视图
    lazy var imageView:HZProgressImageView = {
        let iv = HZProgressImageView()
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        return iv
    }()
    
//    首页视图控制器中的配图视图--本质上HomeVc的cell对其进行强引用
    weak var picView:StatusPictureView?
    
//    准备动画
    func prepareAnimator(picView:StatusPictureView, fromRect:CGRect,toRect:CGRect,url:NSURL){
        
        self.picView = picView
        self.fromRect = fromRect
        self.toRect = toRect
        self.url = url
    }
    
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = true
        return self
    }
    
/// 返回提供解除dismiss转场动画的对象
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = false
        return self
    }
}

// MARK:---PhotoBrowserAnimator
extension PhotoBrowserAnimator:UIViewControllerAnimatedTransitioning{

//  返回转场动画时长
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
    }
    
// 专门实现转场动画效果---一旦实现了此方法,程序员必须完成动画效果
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
        let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
        
        printLog(fromVC)
        printLog(toVC)
        
        isPresented ? presentAnim(transitionContext) : dismissAnim(transitionContext)
    }
    
//    实现解除转场动画
    private func dismissAnim(transitionContext: UIViewControllerContextTransitioning){
        
        let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! PhotoBrowserViewController
        
//        通过控制器获得内部的imageView
        let imageView = fromVC.currentImageView
        let indexPath = fromVC.currentImageIndex
        
        let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
        fromView.removeFromSuperview()
        
        transitionContext.containerView()?.addSubview(imageView)
//        imageView.frame = toRect
        imageView.center = fromView.center
//        参加imageView的形变参数---将fromVc的view的缩放形变叠加到imageView上
        let scale = fromVC.view.transform.a
        imageView.transform = CGAffineTransformScale(imageView.transform, scale, scale)
        imageView.alpha = scale
        
        UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
            
//           fromView.alpha = 0
            
//            imageView.frame = self.fromRect
//            单纯修改最外侧的View的frame无法达到预期的效果
            imageView.frame = self.picView!.screenRect(indexPath)
            imageView.alpha = 1.0
            
            },completion:{(_)-> Void in
                
//              fromView.removeFromSuperview()
                imageView.removeFromSuperview()
                
            transitionContext.completeTransition(true)
})
}

/// 实现model展现动画
    private func presentAnim(transitionContext: UIViewControllerContextTransitioning) {
//        1.将imageView添加到容器视图中
        transitionContext.containerView()?.addSubview(imageView)
        imageView.frame = fromRect

//        2.用sdWebImage异步下载图像
        imageView.sd_setImageWithURL(url, placeholderImage: nil, options: [SDWebImageOptions.RetryFailed], progress: { (current, total) -> Void in
            
            print("\(NSThread.currentThread())---\(total)---\(current))")
            
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.imageView.progress = CGFloat(current) / CGFloat(total)
            })
            
            }) { (_, error, _, _) -> Void in
//               判断是不是有错误
                if error != nil{
                    transitionContext.completeTransition(true)
                    return
                }
                UIView.animateWithDuration(self.transitionDuration(transitionContext), animations: { () -> Void in
                    self.imageView.frame = self.toRect
                    },completion:{(_)->Void in
                        
                    let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
                    transitionContext.containerView()?.addSubview(toView)
                    
//                    将imageView从界面上删除
                    self.imageView.removeFromSuperview()
                    
//                    声明动画完成
                    transitionContext.completeTransition(true)
                })
        }
        
        }
}
























